package cn.knet.excel.imp.knetexceltool.task;

import cn.knet.excel.imp.knetexceltool.DTO.KnetBgdataCompanyBase;
import cn.knet.excel.imp.knetexceltool.service.KnetBgdataCompanyBaseService;
import cn.knet.excel.imp.knetexceltool.thread.CorpImpThread;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.util.Collection;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.LongAdder;

@Service
@Slf4j
public class KnetBgdataImportTask {

    @Resource
    private KnetBgdataCompanyBaseService knetBgdataCompanyBaseService;

    @Value("${excel.dir}")
    private String srcFile;


   @Scheduled(cron = "${task.excel.imp}")
    public void startImp() throws Exception {
        LongAdder okAdder = new LongAdder();
        LongAdder failAdder = new LongAdder();
        readDir(srcFile, KnetBgdataCompanyBase.class, okAdder, failAdder);
    }

    public  void readDir(String dir_excelPath, Class<KnetBgdataCompanyBase> corpClass, LongAdder okAdder, LongAdder failAdder) throws Exception {
        log.info(String.format("====starting  from dir[%s] import excel====", dir_excelPath));
        long stime = System.currentTimeMillis();
        File srcFile = new File(dir_excelPath);
        if (srcFile.exists()) {
            Collection<File> files = FileUtils.listFiles(srcFile, new String[]{"xlsx", "xls"}, false);
            int fcount = 1;
            ExecutorService exector = Executors.newFixedThreadPool(10);
            for (File file : files) {
                /**
                 * 因为文件太多，使用多线程的方式批量处理
                 */
                exector.submit(new CorpImpThread(file, fcount, 2, knetBgdataCompanyBaseService, okAdder, failAdder));
                fcount++;
            }

            exector.shutdown();
            //保证任务全部执行完
            while (!exector.awaitTermination(10, TimeUnit.MINUTES)) {
                System.out.println("**** please wait,in importing.... ****");
            }
            log.info(String.format("<<<<所有excel都已经处理完毕 总计入库 total_ok_fail[%s_%s_%s]>>>>", okAdder.sum() + failAdder.sum(), okAdder.sum(), failAdder.sum()));
        } else {
            throw new Exception("你输入的文件路径不存在");
        }
        long etime = System.currentTimeMillis();
        log.info(String.format("====ending  from dir[%s] import excel====total-time[%s]秒", dir_excelPath, (etime - stime) / 1000d));
    }

}
